//
//  JZContactViewController.m
//  QuanZiChat
//
//  Created by 张洪林 on 15/11/17.
//  Copyright © 2015年 ZhongHongLin. All rights reserved.
//

#import "JZContactViewController.h"
#import "JZAddFriendViewController.h"
#import "ContactManManager.h"
#import "ContactTableViewCell.h"
#import "ContactInfo.h"
#import "JZDetailedViewController.h"
#import "NameAddViewController.h"
#import "FrindManage.h"
#import "TalkManage.h"
#import "User.h"
#import "Friend.h"
#import "NSString+StringToPinyin.h"
#import "NSString+Characters.h"
#import <RongIMKit/RongIMKit.h>


@interface JZContactViewController ()<UITableViewDataSource,UITableViewDelegate,reloadDataDelegate>
@property(nonatomic,strong)NSMutableDictionary *dic;
@property(nonatomic,strong)NSMutableArray *Array;
@property(nonatomic,strong)NSArray *keyArray;
@property(nonatomic,strong)NSString *myname;
@property(nonatomic,strong)User *user;


@end

@implementation JZContactViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.Array removeAllObjects];
    self.keyArray = [NSArray array];
    self.dic = [NSMutableDictionary dictionary];
    //获取当前用户名
    AVUser *currentUser = [AVUser currentUser];
    self.myname = currentUser.username;
    self.tabBarController.tabBar.hidden = NO;
    NSString *str = [NSString stringWithFormat:@"%@的联系人",self.myname];
    self.navigationItem.title = str;
    
    NSArray * array = [[TalkManage defulManage] getbackFriendMessageFromCocaDataWithUsername:self.myname];
    User *user = [array lastObject];
    for (Friend *friend in user.userfrineds) {
        //获取首字母大写
        NSString *Frist = [[[friend.friendname pinyinString:friend.friendname] substringToIndex:1] uppercaseString];
        if ([self.dic.allKeys containsObject:Frist]) {
            //取出首字母对应的数组
            NSMutableArray *GroupArray = self.dic[Frist];
            //添加
            [GroupArray addObject:friend];
        }else{
            //不包含是创建数组并添加key
            NSMutableArray *GroupArray = [NSMutableArray arrayWithObjects:friend, nil];
            [self.dic setObject:GroupArray forKey:Frist];
        }
    }
    //将包含dic的Allkey排序
    self.keyArray = [self.dic.allKeys sortedArrayUsingComparator:^NSComparisonResult(NSString * obj1, NSString * obj2) {
        return [obj1 compare:obj2];
    }];
    for (Friend *frend in user.userfrineds) {
        [self.Array addObject:frend];
    }
    [self.tableview reloadData];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blueColor];
    self.Array = [NSMutableArray array];
    self.dic = [NSMutableDictionary dictionary];
    self.parentViewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"找你玩" style:(UIBarButtonItemStylePlain) target:self action:@selector(clickBarButtonAction:)];
    
    [self.tableview setSeparatorColor:[UIColor clearColor]];
    
    
    //判断是否要打开User表
    if ([[TalkManage defulManage] getbackFriendMessageFromCocaDataWithUsername:[AVUser currentUser].username].count > 0) {
        self.user = [[TalkManage defulManage] getbackFriendMessageFromCocaDataWithUsername:[AVUser currentUser].username].lastObject;
    }else{
        self.user = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:[TalkManage defulManage].managedObjectContext];
    }
    
    //判断是否要从网络获取数据
    AVUser *user = [AVUser currentUser];
    NSArray *array = [user objectForKey:@"friends"];
    if(self.user.userfrineds.count != array.count){
        [[FrindManage defulManager] StoreFriendMessageWithUser:self.user Handle:^{
            [self.tableview reloadData];
        }];
    }
}

- (IBAction)didClickAdd:(id)sender {
    JZAddFriendViewController *addVC = [self.storyboard instantiateViewControllerWithIdentifier:@"JZAddFriendViewController"];
    NameAddViewController *nameadd = [self.storyboard instantiateViewControllerWithIdentifier:@"NameAddViewController"];
    nameadd.Mydelegate = self;
    [self.navigationController pushViewController:addVC animated:YES];
}


//实现方法(页面刷新)
-(void)buttonRelead{
    NSArray * array = [[TalkManage defulManage] getbackFriendMessageFromCocaDataWithUsername:self.myname];
    User *user = array[0];
    for (Friend *friend in user.userfrineds) {
        [self.Array addObject:friend];
    }
    [self.tableview reloadData];
}

#pragma mark ================ TableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return [self.dic allKeys].count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSString * firstName = self.dic.allKeys[section];
    
    NSArray *array = self.dic[firstName];
    return array.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ContactTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    NSString * firstName = self.dic.allKeys[indexPath.section];
    
    Friend * friend = self.dic[firstName][indexPath.row];
    
    cell.fend = friend;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    JZDetailedViewController *friends = [self.storyboard instantiateViewControllerWithIdentifier:@"JZDetailedViewController"];
    NSArray *array = self.dic[self.dic.allKeys[indexPath.section]];
    Friend *contact = array[indexPath.row];
    friends.UserID = contact.friendID;
    friends.UserName = contact.friendname;
    [self.navigationController pushViewController:friends animated:YES];
}

//设置分区头标题
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return self.dic.allKeys[section];
}




//左侧按钮点击方法，打开关闭抽屉

-(void)clickBarButtonAction:(UIBarButtonItem *)barButtonItem{
    
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
